﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common;
using Newtonsoft.Json;
using System.Configuration;
using Newtonsoft.Json.Linq;
using System.Xml;
using System.Collections;

namespace SendCommissioningData
{
    class SendCommissioningDataMethod
    {
        private const string m_OutERPCommiType = "OutERPCommiType";
        private const string m_TempCommiType = "TempCommiType";
        private const string m_InstroeCommiType = "InstroeCommiType";
        //方法入口
        public void RunMain()
        {
            //send_workHour_Recive();
            //return;

            ////1.获取已经转出，但没有出库单号的数据
            //DataTable bpmDt = Get_BPM_CommissioningData(null, "bpm");
            ////2.推送给bpm系统，postData
            //if (bpmDt != null && bpmDt.Rows.Count > 0)
            //{
            //    Send_pbmdata(bpmDt);
            //}
            ////3.获取有出库单号的，但没有推送给外包系统的数据
            //DataTable wbDt = Get_WB_CommissioningData(null, "wb");
            ////4.推送给外包系统，postData
            //if (wbDt != null && wbDt.Rows.Count > 0)
            //{
            //    Send_WBdata(wbDt);
            //}

            //推送出库到ERP add by zhangrj 2023-5-30
            DataTable dtERPCommi = GetContainerToERPDatas();
            if (dtERPCommi != null && dtERPCommi.Rows.Count > 0)
            {
                SendERPForOutCommiData(dtERPCommi);
            }

            //临时外委推送ERP add by zhangrj 2022-11-30
            DataTable dtTempCommi = GetContainerTempCommiData();
            if (dtTempCommi.Rows.Count > 0)
            {
                SendErpForTempCommi(dtTempCommi);
            }
            //入库外委推送BPM add by zhangrj 2022-11-30
            DataTable dtInstoreCommi = GetContainerInstoreCommiData();
            if (dtInstoreCommi.Rows.Count > 0)
            {
                SendBPMForInstoreCommi(dtInstoreCommi);
            }
        }

        #region 调用--BPM和WB--接口
        /// <summary>
        /// 推送给bpm系统
        /// </summary>
        /// <param name="dt"></param>
        public void Send_pbmdata(DataTable dt)
        {
            foreach (DataRow row in dt.Rows)
            {
                Dictionary<string, object> mainDic = getDictionary("bpm", row);
                DataTable itemDT = Get_BPM_CommissioningData(row, "bpmde");
                mainDic["ITEMS"] = itemDT;
                var JsonStr = JsonConvert.SerializeObject(mainDic);
                BpmGxww.GxwwApi api = new BpmGxww.GxwwApi();
                try
                {
                    var re = api.busiService("1001", JsonStr);
                    LogHelp.WriteLog(re);
                    var JsonObj = JObject.Parse(re);
                    //记录日志表
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",row["togetherflag"].ToString()},{"RecordType","sendCommiOutBPM"},
                        {"SendXml",JsonStr},{"ResXml",re},{"IsSuccess",JsonObj["mtype"].ToString() =="S"?"0":"1"},
                        {"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                    OracleDAL.InserOtherSystemRecord(recordPara);
                    if (JsonObj["mtype"].ToString() == "S")//返回更新
                    {
                        updateBpmCommissioningData(JsonObj["msg"].ToString(), row["togetherflag"].ToString());
                    }
                    else
                    {
                        updateBpmCommissioningData("", row["togetherflag"].ToString());
                    }
                }
                catch (Exception ex)
                {
                    LogHelp.WriteError("调用bpm系统接口失败：", ex);
                }
            }
        }
        /// <summary>
        /// 推送给外包系统
        /// </summary>
        /// <param name="dt"></param>
        public void Send_WBdata(DataTable dt)
        {
            foreach (DataRow row in dt.Rows)
            {
                Dictionary<string, object> mainDic = new Dictionary<string, object>();
                Dictionary<string, object> ADic = getDictionary("", row);
                List<Dictionary<string, object>> BDicList = new List<Dictionary<string, object>>();
                DataTable ddt = Get_WB_CommissioningData(row, "wbde");
                foreach (DataRow drow in ddt.Rows)
                {
                    var BDic = getDictionary("b", drow);
                    var proListDic = new List<Dictionary<string, object>>();
                    DataTable proDT = Get_WB_CommissioningData(drow, "wbpro");
                    foreach (DataRow ddrow in proDT.Rows)
                    {
                        proListDic.Add(getDictionary("process", ddrow));
                    }
                    BDic["PROCESS_ITEMS"] = proListDic;//process_items
                    BDicList.Add(BDic);
                }
                mainDic.Add("DataA", ADic);
                mainDic.Add("DataB", BDicList);
                var WBUrl = ConfigurationManager.AppSettings["WBUrl"];
                try
                {
                    var JosnStr = JsonConvert.SerializeObject(mainDic);
                    LogHelp.WriteLog("上传外包数据：" + JosnStr);
                    SCMservice.CicadaForErpWebServiceService wbservice = new SCMservice.CicadaForErpWebServiceService();
                    var rspStr = wbservice.PostData("460-MES", "inventoryout_create", JosnStr);
                    LogHelp.WriteLog("上传外包数据返回结果：" + rspStr);
                    var JsonObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(rspStr);
                    //记录日志表
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",row["togetherflag"].ToString()},{"RecordType","sendCommiOutWB"},
                        {"SendXml",JosnStr},{"ResXml",rspStr},{"IsSuccess",JsonObj["Status"].ToString() =="1"?"0":"1"},
                        {"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                    OracleDAL.InserOtherSystemRecord(recordPara);

                    updateSCMCommissioningData(row["togetherflag"].ToString());
                }
                catch (Exception ex)
                {
                    LogHelp.WriteError("调用外包接口失败：", ex);
                }

            }
        }

        /// <summary>
        /// 查询bpm
        /// </summary>
        /// <param name="row"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public DataTable Get_BPM_CommissioningData(DataRow row, string type)
        {
            try
            {
                //bpm  主数据
                string strSql = @"select distinct c.CONTAINERTYPE,e.FULLNAME USERNAME,e.EMPLOYEENAME USERNO,f.FACTORYNAME DEPTMAME,u.ATTRIBUTEVALUE DEPTNO,c.togetherflag
                         ,cc.outsourcpactno CONNR,cc.lifnr,cc.lname，cc.outsourcorder ebeln,c.PRODUCTNAME MATNR,c.PRODUCTDESCRIPTION MAKTX,c.familylistnames EXTWG,to_char(cc.outdate,'yyyy-MM-dd') BLDAT,
                         to_char(cc.NEEDCOMPLETEDATE,'yyyy-MM-dd') demand_date
                         FROM  CONTAINERCOMMISSIONING cc  
                         LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =cc.OUTEMPLOYEEID
                         LEFT JOIN FACTORY f ON f.FACTORYID =cc.FACTORYID 
                         LEFT JOIN USERATTRIBUTE u ON u.PARENTID =f.FACTORYID AND u.USERATTRIBUTENAME ='分厂代码'
                         LEFT JOIN CONTAINERCURRENTINFO c ON c.CONTAINERID =cc.CONTAINERID 
                         WHERE  cc.ISUSE=0 AND nvl(cc.issendbpm,0)='0' and cc.outsourcpactno is not null and cc.lifnr is not null and cc.lname is not null
                         --and c.togetherflag like 'S21.43.0127/2201%' ";
                if (type == "bpmde")//bpm 明细数据 
                {
                    strSql = @"SELECT  c.MFGORDERNAME AUFNR,c.PRODUCTNAME MATNR,c.PRODUCTDESCRIPTION MAKTX,cc.outsourcorder ebeln,cl.outsourcorderrownum EBELP,cc.outsourcpactno CONNR
                     ,substr(decode(csb.workflowstepname,null,w.workflowstepname,csb.workflowstepname),0,instr(decode(csb.workflowstepname,null,w.workflowstepname,csb.workflowstepname),'-',1,1)-1) VORNR_HEAD
                     ,substr(decode(csb.workflowstepname,null,w.workflowstepname,csb.workflowstepname),instr(decode(csb.workflowstepname,null,w.workflowstepname,csb.workflowstepname),'-',1,1)+1) LTXA1_HEAD,
                     ''VORNR_SUB,''LTXA1_SUB,c.CONTAINERNO CHARG
                     ,CASE WHEN c.containertype != '3' THEN SUM(nvl(CC.OUTQTY,0)) ELSE cc.outqty END ERFMG,'' ERFME, decode(CC.ISUSE,1,'X','') LOEKZ,''ZMEMO,w.workflowstepname, CASE WHEN c.containertype != '7' THEN  wm_concat(cf.qualificationnum) ELSE wm_concat(c1.qualificationnum) END CHARGSXH
                     FROM CONTAINERCOMMISSIONING CC
                     LEFT JOIN ContainerCommiDetail cl ON cl.containercommissioningid=cc.containercommissioningid
                     LEFT JOIN WORKFLOWSTEP w ON w.WORKFLOWSTEPID =cl.WORKFLOWSTEPID 
                     LEFT JOIN Workflow wf ON w.workflowid = wf.workflowid
                     LEFT JOIN CONTAINERCURRENTINFO c ON c.CONTAINERID =CC.CONTAINERID
                     LEFT JOIN container c1 ON c1.containerid = c.containerid
                     LEFT JOIN container cf ON cf.parentcontainerid = c.containerid
                     LEFT JOIN containersubcontainer csb On csb.subcontainerid=cc.containerid
                     where cc.isuse=0 and cl.isuse=0 and  c.togetherflag='" + row["togetherflag"].ToString() + "'group by c.MFGORDERNAME,c.PRODUCTNAME,c.PRODUCTDESCRIPTION,c.CONTAINERNO,cc.OUTQTY,CC.ISUSE,w.workflowstepname,csb.workflowstepname,cc.outsourcorder,cl.outsourcorderrownum,cc.outsourcpactno,cc.outsourcpactvaliddate,c.containertype";
                }
                DataTable myDS = OracleHelper.QueryTable(strSql, null);
                return myDS;
            }
            catch (Exception e)
            {
                return null;
            }

        }

        /// <summary>
        /// 查询外委--出库单信息
        /// </summary>
        /// <param name="sendTye"></param>
        /// <returns></returns>
        public DataTable Get_WB_CommissioningData(DataRow row, string Type)
        {
            try
            {
                string strSql = @" select  distinct cc.outsourcoutno inventory_out_no,to_char(cc.outdate,'yyyy-MM-dd') data_date,cc.outsourcpactno contract_no,c.CONTAINERTYPE,cc.isuse del_flag,cc.lifnr supplier_code,cc.lname supplier_name,
                         e.FULLNAME create_by_name,e.EMPLOYEENAME create_by,to_char(cc.outdate,'yyyy-MM-dd hh24:mi:ss') create_time, u.ATTRIBUTEVALUE dept_code,c.togetherflag,'1' apply_type,
                         e.FULLNAME confirm_user,e.EMPLOYEENAME confirm_user_code
                         FROM  CONTAINERCOMMISSIONING cc  
                         LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =cc.OUTEMPLOYEEID
                         LEFT JOIN FACTORY f ON f.FACTORYID =cc.FACTORYID 
                         LEFT JOIN USERATTRIBUTE u ON u.PARENTID =f.FACTORYID AND u.USERATTRIBUTENAME ='分厂代码'
                         LEFT JOIN CONTAINER c ON c.CONTAINERID =cc.CONTAINERID
                         WHERE  cc.ISUSE=0 and nvl(cc.issendscm,0)='0' and nvl(cc.issendbpm,0)='1' and cc.NEEDCOMPLETEDATE is NOT NULL  
                         AND cc.outsourcoutno IS NOT NULL AND cc.lifnr IS NOT null AND cc.auditresult = '40'
                         --and c.togetherflag like '%S21.43.0127%'";

                if (Type == "wbde")
                {
                    strSql = @" select  cc.outsourcorder purchase_order_no,cc.isuse del_flag, e.FULLNAME create_by_name,e.EMPLOYEENAME create_by,to_char(cc.outdate,'yyyy-MM-dd hh24:mi:ss') create_time,
                           CASE WHEN cci.containertype != '3' THEN SUM(nvl(CC.OUTQTY,0)) ELSE cc.outqty END out_quantity
                          ,cci.mfgordername process_application_code,p.description material_name,p.materialcode material_code,cci.productname part_number
                          ,cci.containerno batch_no,
                           CASE WHEN cci.containertype != '7' THEN  wm_concat(cf.qualificationnum) ELSE wm_concat(c1.qualificationnum) END serial_no,
                          cci.togetherflag
                          ,to_char(cc.NEEDCOMPLETEDATE,'yyyy-MM-dd') demand_date,cc.OUT_WEIGHT,cc.UNIT_QUANITY
                         FROM  CONTAINERCOMMISSIONING cc  
                         LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =cc.OUTEMPLOYEEID
                         LEFT JOIN Containercurrentinfo cci ON cci.containerid=cc.containerid
                         LEFT JOIN container c1 ON c1.containerid = cci.containerid
                         LEFT JOIN product p on p.productid=cci.productid
                           LEFT JOIN container cf ON cf.parentcontainerid = cci.containerid
                         WHERE  cc.ISUSE=0 AND cci.togetherflag ='" + row["togetherflag"].ToString() + "'";
                    strSql += "group by cc.isuse,e.FULLNAME,e.EMPLOYEENAME,cc.outdate,cc.outqty,cci.mfgordername,p.description,cci.productname,cci.containerno,p.materialcode,cci.togetherflag,cc.outsourcorder,cc.NEEDCOMPLETEDATE,cc.OUT_WEIGHT,cc.UNIT_QUANITY,cci.containertype";
                }
                if (Type == "wbpro")
                {
                    //查询--工序明细
                    strSql = @"SELECT distinct ccd.outboundrownum inventory_out_row_num,ccd.outsourcorderrownum purchase_order_row_num,substr(ws.workflowstepname,0,instr(ws.workflowstepname,'-',1,1)-1) process_no
                         ,substr(ws.workflowstepname,instr(ws.workflowstepname,'-',1,1)+1) process_name
                          from CONTAINERCOMMISSIONING cc  
                         LEFT JOIN containercommidetail ccd ON ccd.containercommissioningid=cc.containercommissioningid
                         LEFT JOIN Containercurrentinfo cci ON cci.containerid=cc.containerid
                         LEFT JOIN workflowstep ws ON ws.workflowstepid=ccd.workflowstepid
                         where cc.isuse=0 and ccd.isuse=0 and nvl(cc.issendscm,0)='0' and nvl(cc.issendbpm,0)='1' 
                         and cci.togetherflag='" + row["togetherflag"].ToString() + "'";
                }
                DataTable myDS = OracleHelper.QueryTable(strSql, null);
                return myDS;
            }
            catch (Exception e)
            {
                return null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        public Dictionary<string, object> getDictionary(string type, DataRow row)
        {
            Dictionary<string, object> strList = new Dictionary<string, object>();
            string keys = @"inventory_out_no,data_date,supplier_code,supplier_name,contract_no,confirm_user_code,confirm_user,apply_type,remarks,del_flag,create_by,create_time,update_by,update_by_name,update_time,dept_code";
            if (type == "b")
            {
                keys = @"purchase_order_no,apply_no,process_application_code,material_code,part_number,material_name,batch_no,serial_no,out_quantity,unit_quantity,unit_price,demand_date,del_flag,create_by,create_by_name,create_time,out_weight,process_items";
            }
            if (type == "process")
            {
                keys = @"inventory_out_row_num,purchase_order_row_num,process_no,process_name,sub_process_no,sub_process_name";
            }
            if (type == "bpm")
            {
                keys = @"USERNO,USERNAME,DEPTNO,DEPTMAME,EBELN,CONNR,LIFNR,LNAME,MATNR,MAKTX,EXTWG,BLDAT,DEMAND_DATE,ITEMS";
            }
            foreach (var key in keys.Split(','))
            {
                if (row.Table.Columns.Contains(key))
                {
                    strList.Add(key.ToString().ToUpper(), row[key].ToString());
                }
                else
                {
                    strList.Add(key.ToString().ToUpper(), "");
                }
            }
            return strList;
        }

        /// <summary>
        /// 更新--issendbpm
        /// </summary>
        /// <param name="bpmmsg"></param>
        /// <param name="togetherflag"></param>
        /// <returns></returns>
        public Boolean updateBpmCommissioningData(string bpmmsg, string togetherflag)
        {
            bool result = false;
            try
            {
                var updateStr = @"  update CONTAINERCOMMISSIONING ccm set issendbpm=1,BPMID='" + bpmmsg + "' where ccm.isuse=0 and ccm.containername like '" + togetherflag + "%' ";
                result = OracleHelper.ExecuteSql(updateStr) > 0;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        /// <summary>
        /// 更新--issendscm
        /// </summary>
        /// <param name="bpmmsg"></param>
        /// <param name="togetherflag"></param>
        /// <returns></returns>
        public Boolean updateSCMCommissioningData(string togetherflag)
        {
            bool result = false;
            try
            {
                var updateStr = @"update CONTAINERCOMMISSIONING ccm set issendscm=1 where ccm.isuse=0 and ccm.issendbpm=1 and nvl(ccm.bpmid,0)<>'0' and ccm.containername like '" + togetherflag + "%' ";
                result = OracleHelper.ExecuteSql(updateStr) > 0;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        #endregion

        #region 出库推送ERP
        /// <summary>
        /// 获取需要推送到ERP的外委数据
        /// </summary>
        /// <returns></returns>
        public DataTable GetContainerToERPDatas()
        {
            try
            {
                string strSql = string.Format(@"SELECT c.containerno,c.containername,c.containerid,c.productname,c.mfgordername,c.togetherflag,c.workflowid,
                           c.productid,c.containertype,cc.outqty,cc.containercommissioningid FROM containercommissioning cc 
                           LEFT JOIN containercurrentinfo c ON c.containerid = cc.containerid
                           WHERE cc.ISUSE=0 AND nvl(cc.IsSendScm,0)='0' and cc.outsourcpactno is not null and cc.lifnr is not null and cc.lname is not null
                           AND NOT EXISTS (SELECT 1 FROM writetoerprecord w WHERE w.recordid = cc.containercommissioningid AND w.recordtype = '{0}')", m_OutERPCommiType);
                return OracleHelper.QueryTable(strSql, null);
            }
            catch (Exception e)
            {
                LogHelp.WriteError("外委推送ERP查询sql报错：", e);
                return null;
            }
        }
        /// <summary>
        /// 推送出库到ERP
        /// </summary>
        /// <param name="dtMain"></param>
        public void SendERPForOutCommiData(DataTable dtMain)
        {
            ContainerToERP.PS_SAPServicesHttpService sap = new ContainerToERP.PS_SAPServicesHttpService();
            ContainerToERP.ErpAndAppSyncData mm = new ContainerToERP.ErpAndAppSyncData();


            DataTable dtContainer = dtMain.DefaultView.ToTable(true, "mfgordername", "togetherflag", "workflowid", "productid", "containertype");//按照大批次、件号、工艺路线去重（针对单件单卡，单件单卡只推送一次）
            foreach (DataRow item in dtContainer.Rows)
            {
                string selectStr = string.Format("togetherflag='{0}' and workflowid='{1}' and productid='{2}' and mfgordername='{3}'", item["togetherflag"].ToString(),
                                                item["workflowid"].ToString(), item["productid"].ToString(), item["mfgordername"].ToString());
                DataTable drs = dtMain.Select(selectStr).CopyToDataTable();
                DataTable dtCommiId = drs.DefaultView.ToTable(true, "containercommissioningid");//获取该批次下所有的外委ID
                string sendXml = GetSendToERPOutCommiXML(drs);
                mm.ReqMsg = sendXml;
                ContainerToERP.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
                LogHelp.WriteLog("返回的消息：" + result.RespMsg);
                string exxml = result.RespMsg;
                string isSuccess = "", message = "";
                XmlDocument doc = new XmlDocument();
                ArrayList sqlList = new ArrayList();
                doc.LoadXml(exxml);
                isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;//是否成功
                message = "ERP反馈：" + doc.SelectSingleNode("RespMsg/header/message").InnerText;//返回的消息
                if (isSuccess.ToLower() == "true")//接口调用成功
                {
                    foreach (DataRow drID in dtCommiId.Rows)
                    {
                        //更新外委表
                        sqlList.Add("update CONTAINERCOMMISSIONING ccm set ccm.IsSendScm = 1 WHERE ccm.containercommissioningid = '" + drID["containercommissioningid"].ToString() + "'");
                        //记录日志表
                        OracleDAL.InsertSyncRecord(drID["containercommissioningid"].ToString(), m_OutERPCommiType, "成功", 0);
                    }
                }
                else //接口调用失败
                {
                    foreach (DataRow drID in dtCommiId.Rows)
                    {//记录日志表
                        OracleDAL.InsertSyncRecord(drID["containercommissioningid"].ToString(), m_OutERPCommiType, message, 1);
                    }
                }
                OracleHelper.ExecuteSqlTran(sqlList);
            }
        }
        /// <summary>
        /// 获取推送的XML
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string GetSendToERPOutCommiXML(DataTable dt)
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_ERP";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "ZRFC_MES_SERIALNO_RCV";//方法名
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");
            string strData = "<ITEMS>";
            if (dt.Rows[0]["containertype"].ToString() == "7")
            {
                foreach (DataRow item in dt.Rows)
                {
                    strData += "<ITEM>";
                    strData += "<AUFNR>" + dt.Rows[0]["MfgOrderName"].ToString() + "</AUFNR>";//生产订单号
                    strData += "<MATNR>" + dt.Rows[0]["productname"].ToString() + "</MATNR>";//件号
                    strData += "<CHARG>" + dt.Rows[0]["togetherflag"].ToString() + "</CHARG>";//批次号
                    strData += "<MENGE>{0}</MENGE>";//外委数量
                    strData += string.Format("<SERIAL_NO>{0}</SERIAL_NO>", item["containername"].ToString().Replace(item["productname"].ToString() + "/", ""));
                    strData += "</ITEM>";
                }
                int outQty = dt.AsEnumerable().Sum(p => int.Parse(p["outqty"].ToString()));//外委数
                strData = string.Format(strData, outQty);
            }
            else if (dt.Rows[0]["containertype"].ToString() == "3")
            {
                string sql = "SELECT c.containername FROM container c WHERE c.parentcontainerid = '" + dt.Rows[0]["containerid"].ToString() + "' and c.status = 1";
                DataTable dtChild = OracleHelper.QueryTable(sql, null);
                string containerno = dt.Rows[0]["containername"].ToString().Replace(dt.Rows[0]["productname"].ToString() + "/", "");
                foreach (DataRow item in dtChild.Rows)
                {
                    strData += "<ITEM>";
                    strData += "<AUFNR>" + dt.Rows[0]["MfgOrderName"].ToString() + "</AUFNR>";//生产订单号
                    strData += "<MATNR>" + dt.Rows[0]["productname"].ToString() + "</MATNR>";//件号
                    strData += "<CHARG>" + containerno + "</CHARG>";//批次号
                    strData += "<MENGE>" + dt.Rows[0]["outqty"].ToString() + "</MENGE>";//外委数量
                    strData += string.Format("<SERIAL_NO>{0}</SERIAL_NO>", item["containername"].ToString().Replace(dt.Rows[0]["productname"].ToString() + "/", ""));
                    strData += "</ITEM>";
                }
            }
            else
            {
                strData += "<ITEM>";
                strData += "<AUFNR>" + dt.Rows[0]["MfgOrderName"].ToString() + "</AUFNR>";//生产订单号
                strData += "<MATNR>" + dt.Rows[0]["productname"].ToString() + "</MATNR>";//件号
                strData += "<CHARG>" + dt.Rows[0]["containername"].ToString().Replace(dt.Rows[0]["productname"].ToString() + "/", "") + "</CHARG>";//批次号
                strData += "<MENGE>" + dt.Rows[0]["outqty"].ToString() + "</MENGE>";//外委数量
                strData += "<SERIAL_NO></SERIAL_NO>";
                strData += "</ITEM>";
            }
            strData += "</ITEMS>";
            documentNode.AppendChild(doc.CreateCDataSection(strData));
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }
        #endregion

        #region "临时外委"

        /// <summary>
        /// 获取临时外委待推送ERP数据 add by zhangrj 2022-11-30
        /// </summary>
        /// <returns></returns>
        public DataTable GetContainerTempCommiData()
        {
            try
            {
                string sql = @"
SELECT distinct c.mfgordername,s.specno,s.opdesc,cc.containercommissioningid,c.containerid,cc.PurchaseOrganizeName FROM containercommidetail cm
LEFT JOIN containercommissioning cc ON cc.containercommissioningid = cm.containercommissioningid
LEFT JOIN containersubcontainer csc ON csc.subcontainerid = cc.containerid
LEFT JOIN containercurrentinfo c ON c.containerid = CASE WHEN csc.containerid IS NULL THEN cc.containerid ELSE csc.containerid END
LEFT JOIN workflowstep ws ON ws.workflowstepid = CASE WHEN csc.containerid IS NULL THEN cm.workflowstepid ELSE csc.workflowstepid END
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
LEFT JOIN WritetoOtherSystem wr ON wr.parentid = cc.containercommissioningid  AND wr.recordtype = 'TempCommiType'
WHERE c.containerstatus = 1 AND cc.proposedate IS NOT NULL AND cc.outdate IS NULL AND cc.isuse = 0 AND cm.isuse = 0
AND wr.parentid IS NULL
ORDER BY c.containerid ";
                return OracleHelper.QueryTable(sql, null);
            }
            catch (Exception e)
            {
                LogHelp.WriteError("临时外委查询sql报错：", e);
                return null;
            }
        }

        /// <summary>
        /// 推送临时外委数据到ERP add by zhangrj 2022-11-30
        /// </summary>
        /// <param name="dtTemp"></param>
        public void SendErpForTempCommi(DataTable dtTemp)
        {
            ContainerToERP.PS_SAPServicesHttpService sap = new ContainerToERP.PS_SAPServicesHttpService();
            ContainerToERP.ErpAndAppSyncData mm = new ContainerToERP.ErpAndAppSyncData();

            DataTable dtOrder = dtTemp.DefaultView.ToTable(true, "MfgOrderName");//按照订单去重
            foreach (DataRow item in dtOrder.Rows)
            {
                DataTable drs = dtTemp.Select("MfgOrderName='" + item["MfgOrderName"].ToString() + "'").CopyToDataTable();
                DataTable dtCommiId = drs.DefaultView.ToTable(true, "containercommissioningid");//获取该订单下所有的外委ID
                string sendXml = GetSendToErpXMLByTempCommi(drs);
                mm.ReqMsg = sendXml;
                ContainerToERP.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
                LogHelp.WriteLog("返回的消息：" + result.RespMsg);
                string exxml = result.RespMsg;
                string isSuccess = "", message = "";
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(exxml);
                isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;//是否成功
                message = "ERP反馈：" + doc.SelectSingleNode("RespMsg/header/message").InnerText;//返回的消息
                if (isSuccess.ToLower() == "true")//接口调用成功
                {
                    XmlDocument docItem = new XmlDocument();
                    docItem.LoadXml("<Res>" + doc.SelectSingleNode("RespMsg/document").InnerText + "</Res>");//返回的CDATA中存在多个根节点，需要在外面加一个节点包围
                    string rType = docItem.SelectSingleNode("Res/RTYPE").InnerText;
                    foreach (DataRow drID in dtCommiId.Rows)
                    {
                        //记录日志表
                        Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",drID["containercommissioningid"].ToString()},{"RecordType",m_TempCommiType},
                        {"SendXml",sendXml},{"ResXml",exxml},{"IsSuccess",rType=="S"?"0":"1"},
                        {"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                        OracleDAL.InserOtherSystemRecord(recordPara);
                    }
                }
                else //接口调用失败
                {
                    foreach (DataRow drID in dtCommiId.Rows)
                    {//记录日志表
                        Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",drID["containercommissioningid"].ToString()},{"RecordType",m_TempCommiType},
                        {"SendXml",sendXml},{"ResXml",exxml},{"IsSuccess","1"},
                        {"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                        OracleDAL.InserOtherSystemRecord(recordPara);
                    }
                }
            }
        }
        /// <summary>
        /// 获取临时外委推送ERP的XMl add by zhangrj 2022-11-30
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string GetSendToErpXMLByTempCommi(DataTable dt)
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_ERP";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "ZRFC_GXWB_ROUTE_CHANGE";//方法名
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");
            DataTable dtstep = dt.DefaultView.ToTable(true, "MfgOrderName", "specno", "opdesc", "PurchaseOrganizeName");//去重工序、采购组   
            string strData = "<ITEMS>";
            foreach (DataRow item in dtstep.Rows)
            {
                strData += "<ITEM><UTYPE>C</UTYPE>";//变更类型
                strData += "<AUFNR>" + item["MfgOrderName"].ToString() + "</AUFNR>";//生产订单号
                strData += "<VORNR>" + item["specno"].ToString() + "</VORNR>";//母工序号
                strData += "<UVORN></UVORN>";//子工序号
                strData += "<LTXA1>" + item["opdesc"].ToString() + "</LTXA1>";//工序名称
                strData += "<ARBPL></ARBPL>";//工作中心
                strData += "<STEUS>LY06</STEUS>";//控制码
                strData += "<SAKTO></SAKTO>";//成本要素
                strData += "<MATKL></MATKL>";//物料组
                strData += "<EKGRP>" + item["PurchaseOrganizeName"].ToString() + "</EKGRP></ITEM>";//采购组码
            }
            strData += "</ITEMS>";
            documentNode.AppendChild(doc.CreateCDataSection(strData));
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }

        #endregion

        #region "外委入库订单"
        /// <summary>
        /// 获取可入库工序 add by zhangrj 2022-11-30
        /// </summary>
        /// <returns></returns>
        public DataTable GetContainerInstoreCommiData()
        {
            try
            {
                //查询工序完工且是检验序，且上一序是外委已调度
                string sql = @"
SELECT distinct c.mfgordername,s1.specno,s1.opdesc,cc.outsourcorder,cm1.outsourcorderrownum,cc.outsourcpactno,cc.planqty,cc.outqty,uo.uomname,
cc.containercommissioningid,cc.outsourcoutno,c.productname,c.productdescription,c.familylistnames,c1.qualificationnum,cm1.outboundrownum,cm1.outsourcorderrownum,
c.containername,c.containerid,c.productid,DECODE(c.isinstore,'1',c1.mfgworkflowid,c.workflowid) workflowid,c.containerno,c.togetherflag,c.containertype,
csr.checkemployeename,ee.employeename checkemname,ff.factoryname checkemfacname,nvl(csr.lossqty,0) lossqty,nvl(csr.passqty,0) passqty,c.qty,nvl(csr.defectqty,0) defectqty,cc.outemployeeid,cc.outdate,e.fullname,e.employeename,f.factoryname,
u.attributevalue factorycode,cc.lnamejhrname,cc.lnamejhrphone,cc.fevorshr,cc.fhdate,cc.zjfsl,cc.LNAME,e1.fullname fevorshrname
FROM  containersteprecord csr
LEFT JOIN employee ee ON ee.employeeid = csr.checkemployeeid
LEFT JOIN factory ff ON ff.factoryid = ee.orgfactoryid
LEFT JOIN containercurrentinfo c ON c.containerid = csr.containerid
LEFT JOIN container c1 ON c1.containerid = c.containerid
LEFT JOIN uom uo ON uo.uomid = c1.uomid
--连接完工序,且是检验序
LEFT JOIN workflowstep ws ON ws.workflowstepid = csr.workflowstepid
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
--连接上一序是外委已调度
LEFT JOIN workflowstep ws1 ON ws1.workflowid = ws.workflowid AND ws1.sequence = (ws.sequence-1)
LEFT JOIN containercommidetail cm ON cm.workflowstepid = ws1.workflowstepid AND cm.isuse = 0 AND cm.containerid = c.containerid
LEFT JOIN containercommissioning cc ON cc.containercommissioningid = cm.containercommissioningid AND cc.isuse = 0 
LEFT JOIN employee e ON e.employeeid = cc.outemployeeid
LEFT JOIN factory f ON f.factoryid = e.orgfactoryid
LEFT JOIN Userattribute u ON u.parentid = f.factoryid AND u.userattributename = '分厂代码'
LEFT JOIN employee e1 ON e1.employeename = cc.fevorshr
LEFT JOIN containercommidetail cm1 ON cm1.containercommissioningid = cc.containercommissioningid AND cm.isuse = 0
LEFT JOIN workflowstep ws2 ON ws2.workflowstepid = cm1.workflowstepid
LEFT JOIN specbase sb1 ON sb1.specbaseid = ws2.specbaseid
LEFT JOIN spec s1 ON s1.specid = NVL(sb1.revofrcdid,ws2.specid)
LEFT JOIN WritetoOtherSystem wr ON wr.parentid = cc.containercommissioningid AND wr.recordtype = 'InstroeCommiType'
WHERE csr.usecompleted = 1 AND c.containerstatus = 1 AND s.lastcheck = 1 
AND cc.indate IS Not NULL AND cc.outdate IS NOT NULL --AND cc.outsourcoutno IS NOT NULL 
AND cc.IsSendScm = 1 AND wr.parentid IS NULL";
                return OracleHelper.QueryTable(sql, null);
            }
            catch (Exception e)
            {
                LogHelp.WriteError("外委入库查询sql报错：", e);
                return null;
            }
        }

        /// <summary>
        /// 推送入库外委数据到BPM add by zhangrj 2022-12-15
        /// </summary>
        /// <param name="dtInstore"></param>
        public void SendBPMForInstoreCommi(DataTable dtInstore)
        {
            DataTable dtContainer = dtInstore.DefaultView.ToTable(true, "mfgordername", "togetherflag", "workflowid", "productid", "containertype");//按照大批次、件号、工艺路线去重（针对单件单卡，单件单卡只推送一次）
            foreach (DataRow item in dtContainer.Rows)
            {
                string selectStr = string.Format("togetherflag='{0}' and workflowid='{1}' and productid='{2}' and mfgordername='{3}'", item["togetherflag"].ToString(),
                                                item["workflowid"].ToString(), item["productid"].ToString(), item["mfgordername"].ToString());
                DataTable drs = dtInstore.Select(selectStr).CopyToDataTable();
                DataTable dtCommiId = drs.DefaultView.ToTable(true, "containercommissioningid");//获取该批次下所有的外委ID
                string jsonStr = GetSendToBPMJsonForInstoreCommi(drs);
                ArrayList sqlList = new ArrayList();
                sqlList.Clear();
                try
                {
                    BpmGxww.GxwwApi api = new BpmGxww.GxwwApi();
                    var re = api.busiService("3001", jsonStr);
                    LogHelp.WriteLog(re);
                    var JsonObj = JObject.Parse(re);
                    if (JsonObj["mtype"].ToString() == "S")//返回成功
                    {
                        foreach (DataRow drID in dtCommiId.Rows)
                        {
                            //更新外委表
                            sqlList.Add("update CONTAINERCOMMISSIONING ccm set ccm.instorebpmid = '" + JsonObj["msg"].ToString() + "' WHERE ccm.containercommissioningid = '" + drID["containercommissioningid"].ToString() + "'");
                            //记录日志表
                            Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",drID["containercommissioningid"].ToString()},{"RecordType",m_InstroeCommiType},
                        {"SendXml",jsonStr},{"ResXml",re},{"IsSuccess","0"},{"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                            OracleDAL.InserOtherSystemRecord(recordPara);
                            // OracleDAL.InsertSyncRecord(drID["containercommissioningid"].ToString(), m_InstroeCommiType, "成功", 0);
                        }
                    }
                    else
                    {
                        foreach (DataRow drID in dtCommiId.Rows)
                        {
                            //记录日志表
                            Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",drID["containercommissioningid"].ToString()},{"RecordType",m_InstroeCommiType},
                        {"SendXml",jsonStr},{"ResXml",re},{"IsSuccess","1"},{"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                            OracleDAL.InserOtherSystemRecord(recordPara);
                            //OracleDAL.InsertSyncRecord(drID["containercommissioningid"].ToString(), m_InstroeCommiType, "失败", 1);
                        }
                    }
                    OracleHelper.ExecuteSqlTran(sqlList);
                }

                catch (Exception ex)
                {
                    LogHelp.WriteError("调用bpm系统接口失败：", ex);
                }
            }
        }
        /// <summary>
        /// 获取推送BPM的入库外委JSON数据
        /// </summary>
        /// <returns></returns>
        private string GetSendToBPMJsonForInstoreCommi(DataTable dt)
        {
            DataRow dr = dt.Rows[0];
            string containerSeq = "";
            if (dr["containertype"].ToString() == "3")//批量带子序号
            {
                string sql = "SELECT wm_concat(c.qualificationnum) qnums FROM container c WHERE c.parentcontainerid = '" + dr["containerid"].ToString() + "'";
                DataTable dtChild = OracleHelper.QueryTable(sql, null);
                containerSeq = dtChild.Rows.Count > 0 ? dtChild.Rows[0]["qnums"].ToString() : "";
            }
            else if (dr["containertype"].ToString() == "7") //单件单卡
            {
                foreach (DataRow dr1 in dt.Rows)
                {
                    if (!containerSeq.Contains(dr1["qualificationnum"].ToString()))
                    {
                        containerSeq += dr1["qualificationnum"].ToString() + ",";
                    }
                }
                containerSeq = containerSeq.TrimEnd(',');
            }
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("USERNO", dr["employeename"].ToString());//申请人工号
            dic.Add("USERNAME", dr["fullname"].ToString());//申请人姓名
            dic.Add("DEPTNO", dr["factorycode"].ToString());//申请人部门编号
            dic.Add("DEPTNAME", dr["factoryname"].ToString());//申请人部门名称
            dic.Add("EXTWG", dr["familylistnames"].ToString());//型号
            dic.Add("MATNR", dr["productname"].ToString());//件号
            dic.Add("MAKTX", dr["productdescription"].ToString());//名称
            dic.Add("LNAMEJHRNAME", dr["lnamejhrname"].ToString());//交付人姓名
            dic.Add("FEVORSHR", dr["fevorshr"].ToString());//收货人工号
            dic.Add("FEVORSHRNAME", dr["fevorshrname"].ToString());//收货人姓名
            dic.Add("FHDATE", dr["fhdate"].ToString());//到货日期
            dic.Add("ZJFSL", dr["zjfsl"].ToString());//交付数量
            dic.Add("ZHGSL", dr["passqty"].ToString());//合格数量
            dic.Add("MESJYY", dr["checkemname"].ToString());//检验人工号
            dic.Add("MESJYYNAME", dr["checkemployeename"].ToString());//检验人姓名
            dic.Add("MESJYRDEPTNAME", dr["checkemfacname"].ToString());//检验部门名称

            DataTable dtStep = dt.DefaultView.ToTable(true, "specno", "opdesc");//按照工序去重，可防止单件单卡数据全部推送
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            foreach (DataRow drstep in dtStep.Rows)
            {
                DataTable drs = dt.Select("specno='" + drstep["specno"].ToString() + "' and opdesc = '" + drstep["opdesc"].ToString() + "'").CopyToDataTable();

                string passQty = drs.Compute("SUM(passqty)", string.Empty).ToString();//总的合格数
                dic["ZHGSL"] = passQty;

                string zjfsl = drs.Compute("SUM(zjfsl)", string.Empty).ToString();//总的交付数量
                dic["ZJFSL"] = zjfsl;

                string outqty = drs.Compute("SUM(outqty)", string.Empty).ToString();//总的出库数
                string lossqty = drs.Compute("SUM(lossqty)", string.Empty).ToString();//总的报废数

                DataRow item = drs.Rows[0];
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("AITEM", item["outboundrownum"].ToString());//入库项目号（出库单行项目号）
                para.Add("ACODE", item["outsourcoutno"].ToString());//出库单号
                para.Add("FVTXT", item["factoryname"].ToString());//委托分厂
                para.Add("LNAME", item["LNAME"].ToString());//乘揽厂（外委商家）
                para.Add("ERDAT", DateTime.Now.ToString("yyyy-MM-dd"));//入库日期
                para.Add("EBELN", item["outsourcorder"].ToString());//采购订单号
                para.Add("EBELP", item["outsourcorderrownum"].ToString());//项目号
                para.Add("CONNR", item["outsourcpactno"].ToString());//合同号
                para.Add("AUFNR", item["mfgordername"].ToString());//生产订单号
                para.Add("MATNR", item["productname"].ToString());//产品件号
                para.Add("CHARG", item["togetherflag"].ToString());//批次号
                para.Add("VORNR_HEAD", item["specno"].ToString());//工序号
                para.Add("LTXA1_HEAD", item["opdesc"].ToString());//工序名称
                para.Add("VORNR_SUB", "");//子工序号
                para.Add("LTXA1_SUB", "");//子工序名称
                para.Add("REFMG", outqty);//出库数量
                para.Add("ERFMG", passQty);//入库数量（取值合格数）
                para.Add("ZSJSL", "");//试件报废
                para.Add("GASMG", lossqty);//报废数量
                para.Add("ZBZ", item["mfgordername"].ToString());//备注（生产订单号，可修改）
                para.Add("CHARGSXH", containerSeq);//批次顺序号
                para.Add("REFME", item["uomname"].ToString());//计量单位
                list.Add(para);
            }
            dic.Add("ITEMS", list);
            return JsonConvert.SerializeObject(dic);
        }
        #endregion


        //http://10.15.7.69:7800/PS_SAPServices?wsdl
        #region MyRegion
        public void send_workHour_Recive()
        {
            DataTable mydt = getWorkHourData();
            if (mydt == null || mydt.Rows.Count <= 0)
            {
                LogHelp.WriteLog("没有可处理的实作工时数据");
            }
            foreach (DataRow row in mydt.Rows)
            {
                string strXML = CreateXML(row);
                LogHelp.WriteLog("实作工时传参：" + strXML);
                ContainerToERP.PS_SAPServicesHttpService sap = new ContainerToERP.PS_SAPServicesHttpService();
                ContainerToERP.ErpAndAppSyncData mm = new ContainerToERP.ErpAndAppSyncData();
                mm.ReqMsg = strXML;
                ContainerToERP.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
                string resXML = result.RespMsg; //@"<?xml version='1.0' encoding='UTF-8'?><RespMsg><header><sysName>APP_ERP</sysName><isSuccess>true</isSuccess><message>总线服务成功</message></header><document><![CDATA[<RETTYP><RTYPE>S</RTYPE><RTMSG>{3}</RTMSG></RETTYP>]]></document></RespMsg>";
                LogHelp.WriteLog("实作工时接口返回：" + resXML);
                XmlDocument myxml = new XmlDocument();
                myxml.LoadXml(resXML);
                string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                myxml.LoadXml(xml);
                string success = myxml.SelectSingleNode("RETTYP/RTYPE").InnerText;//
                string message = myxml.SelectSingleNode("RETTYP/RTMSG").InnerText;//
                if (!string.IsNullOrWhiteSpace(success) && success == "S")
                {
                    //更新操作
                }
                else
                {
                    LogHelp.WriteLog(message);
                }
            }

        }

        public DataTable getWorkHourData()
        {
            try
            {
                var strSql = @"select '60000058' MATNR,'测试' MAKTX,'0010' VORNR,'' UVORN,'' LTXA1,'9' VGW06,'LYDL' WERKS from dual";
                DataTable myDS = OracleHelper.QueryTable(strSql, null);
                return myDS;
            }
            catch (Exception e)
            {
                return null;
            }
        }
        public string CreateXML(DataRow row)
        {
            var strList = @"MATNR,MAKTX,VORNR,UVORN,LTXA1,VGW06,WERKS";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
                XmlNode ReqNode = doc.CreateElement("ReqMsg");
                XmlNode headerNode = doc.CreateElement("header");
                XmlNode senderNode = doc.CreateElement("sendSysName");
                senderNode.InnerText = "APP_MES";
                XmlNode rcvNode = doc.CreateElement("rcvSysName");
                rcvNode.InnerText = "APP_ERP";
                XmlNode extConfigNode = doc.CreateElement("extConfig");
                XmlNode isReTryNode = doc.CreateElement("isReTry");
                isReTryNode.InnerText = "false";
                XmlNode FunNameNode = doc.CreateElement("FunName");
                FunNameNode.InnerText = "ZRFC_MES_WORKHOUR_RECIVE";

                extConfigNode.AppendChild(isReTryNode);
                extConfigNode.AppendChild(FunNameNode);
                headerNode.AppendChild(senderNode);
                headerNode.AppendChild(rcvNode);
                headerNode.AppendChild(extConfigNode);
                ReqNode.AppendChild(headerNode);
                XmlNode documentNode = doc.CreateElement("document");
                string strData = "";
                foreach (var _key in strList.Split(','))
                {
                    strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key, row[_key].ToString());
                }
                documentNode.AppendChild(doc.CreateCDataSection("<root>" + strData + "</root>"));
                ReqNode.AppendChild(documentNode);
                doc.AppendChild(ReqNode);
                return doc.InnerXml;
            }
            catch (Exception e)
            {
                LogHelp.WriteError("质量问题提起XML", e);
                return string.Empty;
            }
        }
        #endregion
    }
}
